<template>
    <div>
        <el-card>
            <!--      搜索与添加区域-->
            <el-row :gutter="20" style="margin-bottom: 10px">
                <el-col :span="10">
                    <el-input placeholder="请输入内容" v-model="queryInfo.searchInfo" clearable @clear="getSortList">
                        <el-button slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </el-col>
                <div align="right">
                    <el-button @click="exportExcel()" :enterable="false" type="success" size="small">导出文件</el-button>
                </div>
            </el-row>

            <el-table
                    v-show="false"
                    ref="staticsTabRef"
                    :data="garbageData"
                    border
                    style="width: 100%">
                <el-table-column
                        fixed
                        type="index"
                        prop="garbageId"
                        label="#">
                    <!-- width="150">-->
                </el-table-column>
                <el-table-column
                        align="center"
                        prop="garbageName"
                        label="垃圾名称"
                        width="220px">
                    <!--                    width="180">-->
                </el-table-column>
                <el-table-column
                        align="center"
                        prop="sortName"
                        :filters="[{ text: '可回收物', value: '可回收物' },
                    { text: '有害垃圾', value: '有害垃圾' },
                    { text: '厨余垃圾', value: '厨余垃圾' },
                    { text: '其他垃圾', value: '其他垃圾' }]"
                        :filter-method="filterTag"
                        filter-placement="bottom-end"
                        label="分类名称"
                        width="220px">
                </el-table-column>
                <el-table-column
                        align="center"
                        prop="sortInfo"
                        label="分类信息"
                >
                </el-table-column>

                <el-table-column
                        align="center"
                        prop="all"
                        label="出现次数"
                        width="80px"
                >
                </el-table-column>
                <el-table-column
                        align="center"
                        prop="yes"
                        label="答对次数"
                        width="80px"
                >
                </el-table-column>

                <el-table-column
                        align="center"
                        prop="no"
                        label="答错次数"
                        width="80px"
                >
                </el-table-column>
            </el-table>


            <!--        表格-->
            <el-table
                    :data="pageuserlist"
                    border
                    style="width: 100%">
                <el-table-column
                        fixed
                        type="index"
                        prop="garbageId"
                        label="#">
                    <!-- width="150">-->
                </el-table-column>
                <el-table-column
                        align="center"
                        prop="garbageName"
                        label="垃圾名称"
                        width="220px">
                    <!--                    width="180">-->
                </el-table-column>
                <el-table-column
                        align="center"
                        prop="sortName"
                        :filters="[{ text: '可回收物', value: '可回收物' },
                    { text: '有害垃圾', value: '有害垃圾' },
                    { text: '厨余垃圾', value: '厨余垃圾' },
                    { text: '其他垃圾', value: '其他垃圾' }]"
                        :filter-method="filterTag"
                        filter-placement="bottom-end"
                        label="分类名称"
                        width="180px">
                </el-table-column>
                <el-table-column
                        align="center"
                        prop="sortInfo"
                        label="分类信息"
                >
                </el-table-column>

                <el-table-column
                        align="center"
                        prop="all"
                        label="出现次数"
                        width="80px"
                >
                </el-table-column>
                <el-table-column
                        align="center"
                        prop="yes"
                        label="答对次数"
                        width="80px"
                >
                </el-table-column>

                <el-table-column
                        align="center"
                        prop="no"
                        label="答错次数"
                        width="80px"
                >
                </el-table-column>
<!--                <el-table-column-->
<!--                        align="center"-->
<!--                        label="操作"-->
<!--                        width="120px"-->
<!--                >-->
<!--                    <template >-->
<!--                        <el-button @click="exportExcel()" :enterable="false" type="success" size="small">导出文件</el-button>-->
<!--                    </template>-->
<!--                </el-table-column>-->
            </el-table>
            <!--      分页区域-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    :page-sizes="[1, 5, 7, 10]"
                    :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>
        <!--    查看垃圾信息的对话框-->
        <el-dialog
                title="查看垃圾信息"
                :visible.sync="showDialogVisible"
                width="50%" @close="showDialogClosed">
            <!--      内容主体区域-->
            <el-form :model="editForm" ref="editFormRef" status-icon label-width="100px">
                <!--                图片信息-->
                <el-form-item prop="imageUrl" label="垃圾图片">
                    <div style="margin-left: 35%">
                        <el-image
                                style="width: 100px; height: 100px"
                                :src="this.editForm.imageUrl"
                                :fit="fit">
                            <div slot="error"  >
                                <el-image   :lazy="true"  fit="cover"  src="notFound.jpg"  >
                                </el-image>
                            </div>
                            <div slot="placeholder"  >
                                图片被意大利炮轰走了
                            </div>
                        </el-image>
                    </div>
                </el-form-item>
                <el-form-item prop="garbageName" label="垃圾名称">
                    <el-input class="rt-input" v-model="editForm.garbageName" autocomplete="off" disabled></el-input>
                </el-form-item>
                <el-form-item prop="sortName" label="分类名称">
                    <el-input class="rt-input" v-model="editForm.sortName" autocomplete="off" disabled></el-input>
                </el-form-item>
                <el-form-item prop="sortInfo" label="分类信息">
                    <el-input class="rt-input" v-model="editForm.sortInfo" autocomplete="off" disabled></el-input>
                </el-form-item>

            </el-form>
            <!--      底部区域-->
            <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="showDialogClosed">确定</el-button>
        </span>
        </el-dialog>
        <!--    修改垃圾信息的对话框-->
        <el-dialog
                title="修改垃圾信息"
                :visible.sync="editDialogVisible"
                width="50%" @close="editDialogClosed">
            <!--      内容主体区域-->
            <el-form :model="editForm" status-icon ref="editFormRef" label-width="100px" enctype="multipart/form-data">
                <!--                上传图片-->
                <el-form-item style="height: 100px;vertical-align: center" prop="imageUrl" label="上传图片">
                    <el-upload
                            class="avatar-uploader"
                            :auto-upload="false"
                            :http-request="upLoadImage"
                            action=""
                            :show-file-list="false"
                            :on-change="upLoadImage"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="editForm.imageUrl" :src="editForm.imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>

                <el-form-item prop="garbageId" label="垃圾编号">
                    <el-input class="rt-input" v-model="editForm.garbageId" disabled></el-input>
                </el-form-item>
                <el-form-item prop="garbageName" :rules="[{ required: true, message: '名称不能为空'}]" label="垃圾名称">
                    <el-input class="rt-input" v-model="editForm.garbageName"></el-input>
                </el-form-item>
                <el-form-item prop="sortId" label="分类信息">
                    <el-select v-model="editForm.sortId" placeholder="this">
                        <el-option
                                v-for="item in sortData"
                                :key="item.sortId"
                                :label="item.sortName"
                                :value="item.sortId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="createTime" label="创建日期">
                    <el-input class="rt-input" v-model="editForm.createTime" disabled></el-input>
                </el-form-item>
            </el-form>
            <!--      底部区域-->
            <span slot="footer" class="dialog-footer">
              <el-button @click="resetEdit">重置修改</el-button>
              <el-button type="primary" @click="editGarbage">确定修改</el-button>
            </span>
        </el-dialog>

        <!--            新增垃圾信息的对话框-->
        <el-dialog
                title="新增垃圾信息"
                :visible.sync="createDialogVisible"
                width="50%" @close="createDialogClosed">
            <!--      内容主体区域-->
            <el-form :model="editForm" ref="editFormRef" status-icon label-width="100px">

                <!--                上传图片-->
                <el-form-item style="height: 100px;vertical-align: center" prop="imageUrl" label="上传图片">
                    <el-upload
                            class="avatar-uploader"
                            :auto-upload="false"
                            :http-request="upLoadImage"
                            action=""
                            :show-file-list="false"
                            :on-change="upLoadImage"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="editForm.imageUrl" :src="editForm.imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>

                <el-form-item prop="garbageName" :rules="[{ required: true, message: '名称不能为空'}]" label="垃圾名称">
                    <el-input class="rt-input" v-model=editForm.garbageName></el-input>
                </el-form-item>
                <el-form-item prop="sortId" label="分类信息">
                    <el-select v-model="editForm.sortId" placeholder="请选择分类">
                        <el-option
                                v-for="item in sortData"
                                :key="item.sortId"
                                :label="item.sortName"
                                :value="item.sortId">
                        </el-option>
                    </el-select>
                </el-form-item>

            </el-form>
            <!--      底部区域-->
            <span slot="footer" class="dialog-footer">
              <el-button @click="resetCreate">重置</el-button>
              <el-button @click="createGarbage" type="primary">确定</el-button>
            </span>
        </el-dialog>

    </div>
</template>
<style>
    .rt-input /deep/ .el-input__inner {
        color: #6B6C70 !important;
        cursor: pointer;
    }

    .avatar-uploader .el-upload {
        width: 100px;
        height: 100px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        position: relative;
        left: 35%;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
        position: relative;
        top: 35px;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>

<script>
    import FileSaver from 'file-saver';
    import XLSX from 'xlsx';
    export default {
        data() {
            return {

                //  图片
                file:null,
                notFound:'图片走丢了',
                uploadImageUrl: '',
                showImageUrl: '',
                fit: 'fill',
                total: 0,
                sortData: [],
                garbageData: [],
                queryInfo: {
                    searchInfo: '',
                    // 当前页数
                    pagenum: 1,
                    pagesize: 7
                },
                row: '',
                showDialogVisible: false,
                editDialogVisible: false,
                createDialogVisible: false,
                editFormRules: {
                    garbageName: [
                        {
                            require: true,
                            message: '垃圾姓名不能为空',
                            trigger: 'blur'
                        }
                    ]
                },
                editForm: {
                    "imageUrl": '',
                    "garbageId": '',
                    "garbageName": '',
                    "sortId": '',
                    "sortName": '',
                    "sortInfo": '',
                    "createTime": ''
                }
            }
        },
        created() {
            this.getSortList();
        },
        methods: {

            exportExcel() {
                const excelName = '题目统计'
                //excelName --设置导出的excel名称
                //report-table --对应的要导出的el-table的ref名称
                try {
                    const $e = this.$refs['staticsTabRef'].$el;
                    // 如果表格加了fixed属性，则导出的文件会生产两份一样的数据，所以可在这里判断一下
                    let $table = $e.querySelector('.el-table__fixed');
                    if (!$table) {
                        $table = $e;
                    }
                    // 为了返回单元格原始字符串，设置{ raw: true }
                    const wb = XLSX.utils.table_to_book($table, { raw: true });
                    const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' });
                    FileSaver.saveAs(
                        new Blob([wbout], { type: 'application/octet-stream' }),
                        `${excelName}.xlsx`,
                    );
                } catch (e) {
                    if (typeof console !== 'undefined') console.error(e);
                }
            },
            async getSortList() {
                const {data: res} = await this.$http.get('/question/statistic')
                if (res.status !== 200) {
                    return this.$message.error(res.msg + '，获取垃圾信息列表失败!')
                }
                this.garbageData = res.data
                this.total = res.data.length
                console.log(res.data)
            },
            resetEdit() {
                const row = this.row
                this.editForm.imageUrl = row.imageUrl
                this.editForm.garbageId = row.garbageId
                this.editForm.garbageName = row.garbageName
                this.editForm.sortId = row.sortId
                this.editForm.sortName = row.sortName
                this.editForm.sortInfo = row.sortInfo
                this.editForm.createTime = row.createTime
                // console.log(this.garbageData())
                // this.editDialogVisible = false
            },
            resetCreate() {
                this.editForm.imageUrl = null
                this.editForm.garbageId = null
                this.editForm.garbageName = null
                this.editForm.sortId = null
                this.editForm.sortName = null
                this.editForm.sortInfo = null
                this.editForm.createTime = null
            },
            handleClick(row) {
                console.log(row);
            },
            filterTag(value, row) {
                return row.sortName === value
            },
            // 查看垃圾信息的对话框
            showEditDialog(row) {
                this.showDialogVisible = true
                this.$nextTick(() => {
                    this.editForm.imageUrl = row.imageUrl
                    this.showImageUrl = this.editForm.imageUrl
                    this.editForm.garbageId = row.garbageId
                    this.editForm.garbageName = row.garbageName
                    this.editForm.sortId = row.sortId
                    this.editForm.sortName = row.sortName
                    this.editForm.sortInfo = row.sortInfo
                    this.editForm.createTime = row.createTime
                    this.row = row
                })
            },
            // 编辑垃圾信息的对话框
            editEditDialog(row) {
                this.editDialogVisible = true
                this.editForm.imageUrl = row.imageUrl
                this.editForm.garbageId = row.garbageId
                this.editForm.garbageName = row.garbageName
                this.editForm.sortId = row.sortId
                this.editForm.sortName = row.sortName
                this.editForm.sortInfo = row.sortInfo
                this.editForm.createTime = row.createTime
                this.row = row
            },
            // 监听对话框的关闭事件
            showDialogClosed() {
                // this.$refs.editFormRef.resetFields()

                this.showDialogVisible = false
            },
            editDialogClosed() {
                // this.$refs.editFormRef.resetFields()
                this.editDialogVisible = false
            },
            createDialogClosed() {

                // this.$refs.editFormRef.resetFields()
                this.createDialogVisible = false
            },
            // 重置修改

            // 监听 pagesize 改变的事件
            handleSizeChange(newSize) {
                this.queryInfo.pagesize = newSize
                // alert(newSize)
                this.getSortList()
            },
            // 监听页码值改变的事件
            handleCurrentChange(newPage) {
                console.log(newPage)
                // alert(newPage)
                this.queryInfo.pagenum = newPage
                this.getSortList()
            },

            // 修改垃圾信息


            editGarbage() {

                this.$refs.editFormRef.validate(async valid => {
                    // const base64 = reader.readAsDataURL(this.file); //Base6
                    const formData = new FormData()
                    if (this.file!=null){
                        formData.append("file",this.file.raw)
                        formData.append("name","image")
                        formData.append("typeId","image")
                        // console.log(this.file)
                        this.file=null
                        // console.log(formData.get('file'))
                        if (!valid) return
                        const {data: resp} = await this.$http.post('/file/uploadImage', formData)
                        if (resp.status !== 200) {
                            return this.$message.error('图片上传失败！')
                        }
                        // console.log(resp.data.image)
                        this.editForm.imageUrl = resp.data.image
                    }


                    console.log(this.editForm.imageUrl)
                    const {data: res} = await this.$http.put('/garbage/update', {
                        imageUrl: this.editForm.imageUrl,
                        garbageId: this.editForm.garbageId,
                        garbageName: this.editForm.garbageName,
                        sortId: this.editForm.sortId
                    })
                    if (res.status !== 200) {
                        return this.$message.error(res.msg + '，修改失败!')
                    }
                    this.$message.success('修改成功！')
                    this.editDialogVisible = false
                    this.getSortList()

                })
            },
            createDialog() {
                this.createDialogVisible = true
                this.editForm.imageUrl = null
                this.editForm.garbageId = null
                this.editForm.garbageName = null
                this.editForm.sortId = null
                this.editForm.sortName = null
                this.editForm.sortInfo = null
                this.editForm.createTime = null
            },
            // 新增垃圾信息
            createGarbage() {
                this.$refs.editFormRef.validate(async valid => {

                    const formData = new FormData()
                    if (this.file!=null){
                        formData.append("file",this.file.raw)
                        formData.append("name","image")
                        formData.append("typeId","image")
                        this.file=null
                        // console.log(this.file)
                        // console.log(formData.get('file'))
                        if (!valid) return
                        const {data: resp} = await this.$http.post('/file/uploadImage', formData)
                        if (resp.status !== 200) {
                            return this.$message.error('图片上传失败！')
                        }
                        // console.log(resp.data.image)
                        this.editForm.imageUrl = resp.data.image
                    }

                    // console.log(valid)
                    if (!valid) return
                    const {data: res} = await this.$http.post('/garbage/create', {
                        imageUrl: this.editForm.imageUrl,
                        garbageName: this.editForm.garbageName,
                        sortId: this.editForm.sortId
                    })
                    if (res.status !== 200) {
                        return this.$message.error(res.msg + '，创建失败!')
                    }
                    this.$message.success('创建成功！')
                    this.createDialogVisible = false
                    this.getSortList()
                    this.file=null
                })
            },
            //监听图片上传
            handleAvatarSuccess(res, file) {
                this.uploadImageUrl = URL.createObjectURL(file.raw);
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isPng = file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 10;

                if (!isJPG&&!isPng) {
                    this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 10MB!');
                }
                return isJPG && isLt2M;
            },
            //  上传图片
            async upLoadImage(file){
                this.file = file
                this.$message.success('图片上传成功！')
            },

            // 删除垃圾信息
            deleteGarbage(row) {
                this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    // console.log(valid)
                    this.$refs.editFormRef.validate(async valid => {
                        // console.log(valid)


                        // alert(123);
                        const garbageId = row.garbageId
                        const {data: res} = await this.$http.delete('/garbage/delete/' + garbageId)
                        this.getSortList()


                    }).catch(() => {
                        this.getSortList()
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });

                })
            }


        },

        computed: {
            pageuserlist: function () {
                var search = this.queryInfo.searchInfo
                if (search) {
                    return this.garbageData.filter(function (data) {
                        return Object.keys(data).some(function (key) {
                            return String(data[key]).toLowerCase().indexOf(search) > -1
                        })
                    })
                }
                return this.garbageData.slice((this.queryInfo.pagenum - 1) * this.queryInfo.pagesize, this.queryInfo.pagenum * this.queryInfo.pagesize)
            }
        }
    }
</script>
